package com.itheima.aop;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utill.CurrentHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
public class OperateLogAspect {

    @Autowired
    private OperateLogMapper opateLogMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.itheima.flag.Flag)")
    public Object OperateLog(ProceedingJoinPoint joinPoin) throws Throwable {
//        //从jwt中获取令牌
//        String jwt = request.getHeader("token");
//        //解析jwt
//        Claims claims = JwtUtils.parseJWT(jwt);
//        //先将解析出来的jwt转换成String类型的id , 再强转为int类型
//        int id = Integer.parseInt(claims.get("id").toString());

        //从ThreadLocal 令牌中取出登录用户的id

        Integer id = CurrentHolder.getCurrentId();

        //获取操作的类名
        String name = joinPoin.getTarget().getClass().getName();
        //获取方法名
        String methodName = joinPoin.getSignature().getName();
        //获取方法的参数
        Object[] args = joinPoin.getArgs();
        //因为是Object类型所以因该转为字符串类型
        String args1 = Arrays.toString(joinPoin.getArgs());
        //增强前的时间
        long start = System.currentTimeMillis();
        //执行目标方法
        Object result = joinPoin.proceed();
        //放行前清楚
        CurrentHolder.remove();
        //执行后的时间
        long end = System.currentTimeMillis();
        //创建实体类对象
        OperateLog operateLog = new OperateLog();
       // operateLog.setId(null);//因为id是自增的
        operateLog.setOperateEmpId(id); //与上面jwt解析出来的id对应 , 因为获取的是操作者的id
        operateLog.setOperateTime(LocalDateTime.now());//获取当前时间
        operateLog.setClassName(name);//操作类名
        operateLog.setMethodName(methodName);//操作方法名
        operateLog.setMethodParams(args1);//操作的方法参数
        operateLog.setReturnValue(result.toString());
        operateLog.setCostTime((end - start));
        //持久层记录时间
        operateLogMapper.insert(operateLog);
        return result;

    }
}
